import serial
from tool import log, send


def open_com(cfg):
    try:
        ser = serial.Serial()
        ser.port = cfg["port"]
        ser.baudrate = cfg["rate"]
        ser.timeout = None

        ser.open()

        return ser
    except Exception as e:
        log("serial error: %s" % e)
        return None


def read_com(wsn, k, ser, w_queue, d_queue):
    try:
        data = ser.readline()

        data = "%s" % data

        data = data.replace("\r", "").replace("\n", "").replace("\t", "")

        if not data:
            return

        cmd = {k: data}

        send("http://127.0.0.1:9985/plc/put", {"line": "1", "sn": wsn, "v": cmd})

        w_queue.put(cmd)
        d_queue.put(cmd)

    except serial.SerialException as e:
        log("error: %s" % e)


def do_gun(cfg, k, w_queue, d_queue):
    wsn = cfg["wsn"]

    ser = open_com(cfg[k])

    if not ser:
        log("open com error")
        return

    while True:
        try:
            read_com(wsn, k, ser, w_queue, d_queue)
        except Exception as e:
            log("do_com error: %s" % e)
